package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.utils.Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/15.
 */
public class UserChangePhoneSecondActivity extends BaseUIActivity {
	/**
	 * 手机号码
	 */
	@ViewInject(id = R.id.user_account_ed)
	private EditText user_account_ed;
	/**
	 * 验证码
	 */
	@ViewInject(id = R.id.user_code_ed)
	private EditText user_code_ed;
	/**
	 * 发送验证码
	 */
	@ViewInject(id = R.id.btn_send_code)
	private TextView btn_send_code;

	/**
	 * 密码
	 */
	@ViewInject(id = R.id.user_pwd_ed)
	private EditText user_pwd_ed;
	/**
	 * 确定
	 */
	@ViewInject(id = R.id.user_confirm_bt, click = "user_confirm_click")
	private TextView user_confirm_bt;
	private String phone;//输入框中输入的手机号
	private String code;//输入框输入的验证码
	private String pwd_str;//密码
	private TimeCount time; //定时器
	private boolean isSend;//用来防止网络延时后发送验证码


	private int flag = 1;//0 app启动正常进入的   1：已经启动，再次进入登录
	boolean isChangePhone;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_change_phone_second);
		isChangePhone = getIntent().getBooleanExtra(ExtraKeys.Key_Msg1, false);
		if (isChangePhone) {
			((LinearLayout) user_pwd_ed.getParent()).setVisibility(View.GONE);

			setCenter_title(R.string.change_phone);
		} else {
			setCenter_title(R.string.bind_phone);
			((LinearLayout) user_pwd_ed.getParent()).setVisibility(View.VISIBLE);
            user_account_ed.setHint(R.string.bind_phone_hint);
			try {
				flag = getIntent().getIntExtra(ExtraKeys.Key_Msg2, 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		isSend = false;
		sendCodeClick();
		time = new TimeCount(120000, 1000);
	}

	/**
	 * 点击确定绑定手机
	 */
	public void getData_BindPhone() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.User_Key);
		params.put("userName", Utils.getUserAccount(this));
		params.put("phone", phone);
		params.put("code", code);
		if(isChangePhone) {
			params.put("psd","" ) ;
		} else {
			params.put("psd",pwd_str) ;
		}
		GetDataQueue queue = new GetDataQueue();
		queue.setCallBack(callBack);
		queue.setActionName(GetDataConfing.GetAction_SumitForgetphone);
		queue.setWhat(GetDataConfing.what_SumitForgetphone);
		queue.setParamsNoJson(params);
		getDataUtil.getData(queue);
	}

	/**
	 * 发送验证码调用接口
	 */
	public void getData_SendCode() {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.User_Key);
		params.put("userName", Utils.getUserAccount(this));
		params.put("phone", phone);
		GetDataQueue queue = new GetDataQueue();
		queue.setCallBack(callBack);
		queue.setActionName(GetDataConfing.GetAction_SendMessagePhone);
		queue.setWhat(GetDataConfing.what_SendMessagePhone);
		queue.setParamsNoJson(params);
		getDataUtil.getData(queue);
	}

	/**
	 * 数据回调
	 */
	private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {
		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {

				if (ShowGetDataError.isOkAndCodeIsNot1(UserChangePhoneSecondActivity.this,
						entity.getInfo())) {
					if (entity.getWhat() == GetDataConfing.what_SendMessagePhone) {
						time.start();
						btn_send_code.setEnabled(false);
					} else if (entity.getWhat() == GetDataConfing.what_SumitForgetphone) {
						toast.showToast(R.string.change_success);
						Utils.saveUserPhone(mContext,phone);
						setResult(RESULT_OK);
						finish();
					}
				}
			} else {
				ShowGetDataError.showNetError(UserChangePhoneSecondActivity.this);
			}
			loadingToast.dismiss();
		}
	};

	public void user_confirm_click(View view) {
		code = user_code_ed.getText().toString();
		if (!StringUtil.isMobileNO(phone)) {
			toast.showToast(R.string.phone_formal_error);
			return;
		}

		if(TextUtils.isEmpty(code)){
			toast.showToast(R.string.pls_input_code);
			user_code_ed.requestFocus();
			return;
		}
		pwd_str=user_pwd_ed.getText().toString();
		if(!isChangePhone){
		   if(!StringUtil.passwordAuthenticationLength(pwd_str)){
			  toast.showToast(R.string.register_passwordRule);
			   return;
		   } else if (!StringUtil.passwordAuthentication(pwd_str)){
			   toast.showToast(R.string.password_format_error);
			   return;
		   }
		}
		getData_BindPhone();
	}

	/**
	 * 获取验证码（防止网络延时发送多条验证码）
	 */
	public void sendCodeClick() {
		btn_send_code.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				phone = user_account_ed.getText().toString();
				if (!StringUtil.isMobileNO(phone)) {
					toast.showToast(R.string.phone_formal_error);
					return;
				}
				isSend = true;
				getData_SendCode();
			}
		});
	}

	//验证码倒计时
	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			//参数依次为总时长,和计时的时间间隔
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			//计时完毕时触发
			btn_send_code.setText(getString(R.string.revalidation));
			btn_send_code.setClickable(true);
			code = "";
			btn_send_code.setEnabled(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {//计时过程显示
			btn_send_code.setText(millisUntilFinished / 1000 + getString(R.string.second));
		}
	}

	@Override
	public void finish() {
		if (flag == 0) { //app启动进入
			if (MyApplication.getInstance().getAttentionBrands().size() == 0) {
				Intent intentLogin = new Intent(this, AttentionActivity.class);
				intentLogin.putExtra(ExtraKeys.Key_Msg1, flag);
				jumpTo(intentLogin, false);
			} else {
				jumpTo(MainActivity.class, false);
			}
		} else {

		}
		super.finish();
	}
}
